﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinBookKeeping.Models;
using WinBookKeeping.Data;

namespace WinBookKeeping.Utility
{
    public class CommonHelper
    {
        private static readonly IBookKeepingRepository _repository = new BookKeepingRepository();

        public static async Task<List<string>> GetItems(int itemType)
        {
            var items = new List<string>();
            string typeName = itemType == 1 ? "收入" : "支出";
            
            try
            {
                var allItems = await _repository.GetAllItemsAsync();
                items = allItems
                    .Where(i => i.ItemType == typeName)
                    .Select(i => i.ItemName)
                    .ToList();
            }
            catch (Exception ex)
            {
                MessageHelper.Error("获取名目", $"获取名目失败：{ex.Message}");
            }
            
            return items;
        }

        public static async Task<List<RecordInfo>> GetAllRecordList()
        {
            List<RecordInfo> records = new List<RecordInfo>();
            try
            {
                var incomes = await _repository.GetAllIncomesAsync();
                var expenditures = await _repository.GetAllExpendituresAsync();
                int id = 0;

                if (incomes.Count > 0)
                {
                    foreach (var r in incomes)
                    {
                        id += 1;
                        records.Add(new RecordInfo()
                        {
                            Id = id,
                            ItemType = "收入",
                            ItemName = r.ItemName,
                            Description = r.IncomeDesp,
                            Money = r.Money,
                            RecordTime = DateTime.Parse(r.IncomeTime)
                        });
                    }
                }

                if (expenditures.Count > 0)
                {
                    foreach (var r in expenditures)
                    {
                        id += 1;
                        records.Add(new RecordInfo()
                        {
                            Id = id,
                            ItemType = "支出",
                            ItemName = r.ItemName,
                            Description = r.expendDesp,
                            Money = r.Money,
                            RecordTime = DateTime.Parse(r.expendTime)
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                MessageHelper.Error("获取记录", $"获取记录失败：{ex.Message}");
            }
            return records;
        }
    }
}
